package elementos;

import java.awt.Color;
import java.awt.Graphics;   
import java.awt.Graphics2D;
import java.util.ArrayList;

public class Ball implements Movible{
    private float x,y,dx,dy,radio;
    
    public Ball(float x, float y, float dx, float dy, float radio){
        this.x=x;
        this.y=y;
        this.dx=dx;
        this.dy=dy;
        this.radio=radio;
    }
    public void moveTo(float x, float y){
        this.x=x;
        this.y=y;
        this.dx=(dx/Math.abs(dx));
        this.dy=(dy/Math.abs(dy));
    }
    
    public void move(){
        x+=dx;
        y+=dy;
    }
    
    public float getX(){
        return x;
    }
    
    public float getRadio(){
        return radio;
    }
    
    public float getY(){
        return y;
    }
    
    public float getDX(){
        return dx;
    }
    
    public float getDY(){
        return dy;
    }

    public void setDx(float dx) {
        this.dx = dx;
    }

    public void setDy(float dy) {
        this.dy = dy;
    }
    
    public void invertX(){
        dx*=-1;
    }
    public void invertY(){
        dy*=-1;
    }
    
    public void render(Graphics g) {
        //render the ball
        Graphics2D g2 = (Graphics2D)g;
        //g.setBackground(Color.white);
        Color c= g2.getColor();
        g2.setColor(Color.red);
        g2.fillOval((int)(x-radio), (int)(y-radio), (int)(2*radio), (int)(2*radio));
        g2.setColor(c);
    }

    public void add(Drawable d) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void remove(Drawable d) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Drawable getChild(int i) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Drawable collision(Drawable d) {
        if(d instanceof Ball){
        Ball b = (Ball) d;
        //calcular distancia entre centros.
        float xmax = Math.max(this.x, b.getX());
        float xmin = Math.min(this.x, b.getX());
        float ymax = Math.max(this.y, b.getY());
        float ymin = Math.min(this.y, b.getY());
        double dist = Math.sqrt(Math.pow(xmax - xmin, 2) + Math.pow(ymax - ymin, 2));
        //collision
        if (dist <= (double) b.getRadio() * 2) {
            //mirar signos de las velocidades
            if (dx * b.getDX() < 0) {
                invertX();
                b.invertX();
            }
            if (dy * b.getDY() < 0) {
                invertY();
                b.invertY();
            }
            return b;
        }
        }
        return null;
    }        

    @Override
    public void moveObject() {
        this.move();
    }
}
